package com.zisuyi.game.sdk.game

import com.orhanobut.logger.Logger
import com.weilele.mvvm.BuildConfig
import com.weilele.mvvm.MvvmConf
import com.weilele.mvvm.base.helper.success
import com.weilele.mvvm.gson
import com.weilele.mvvm.utils.activity.toast
import com.weilele.mvvm.utils.net.getStringBody
import com.yizisu.library.ad.IAdRewardStatus
import com.zisuyi.game.sdk.base.net.sendHttpByJsonBody
import com.zisuyi.game.sdk.game.bean.AndroidJsBean
import com.zisuyi.game.sdk.game.bean.GameNetworkApiBean
import com.zisuyi.game.sdk.net.bean.BaseGameBean
import com.zisuyi.game.sdk.utils.UserData
import okhttp3.Call
import okhttp3.Callback
import java.io.IOException

/**
 * 发送消息给游戏
 */
fun GameEgret.sendToJs(message: String?) {
    message ?: return
    if (this.appCompatActivity.isDestroyed) {
        if (MvvmConf.IS_DEBUG) {
            Logger.e("${this.appCompatActivity} 已经销毁，以下消息无法发送给JS")
            Logger.json(message)
        }
        return
    }
    if (MvvmConf.IS_DEBUG) {
        Logger.v("-----------------原生发送消息给JS----------------->")
        Logger.json(message)
    }
    appCompatActivity.runOnUiThread {
        callExternalInterface(GameEgret.MESSAGE_SEND_TO_JS, message)
    }
}

/**
 * 发送消息给游戏
 */
fun GameEgret.sendToJs(message: AndroidJsBean?) {
    message ?: return
    sendToJs(gson.toJson(message))
}

fun GameEgret.showGameVideoAd(bean: AndroidJsBean) {
    val ad = gameAd ?: return
    ad.showVideoAd {
        when (it) {
            IAdRewardStatus.Cancel,
            IAdRewardStatus.NoAd -> {
                //发送失败
                bean.message = GameReceiveMessage.VIDEO_FAIL
                bean.code = GameReceiveMessage.ERROR_CODE_SHOW_VIDEO_AD
                bean.json = GameReceiveMessage.VIDEO_FAIL + "|" + bean.json
                "Video Ad loaded fail".toast()
                sendToJs(bean)
            }
            IAdRewardStatus.OpenAd -> {

            }
            IAdRewardStatus.Success -> {
                //发送成功
                bean.message = GameReceiveMessage.VIDEO_SUCCESS
                bean.code = 0
                bean.json = GameReceiveMessage.VIDEO_SUCCESS + "|" + bean.json
                sendToJs(bean)
            }
        }
    }
}

/**
 * 发送网络请求
 */
fun GameEgret.netRequest(message: AndroidJsBean) {
    val bean = gson.fromJson(message.json, GameNetworkApiBean::class.java)
    val api = bean.api
    val params = bean.params
    api.sendHttpByJsonBody(params, method = bean.method).enqueue(object : Callback {
        override fun onFailure(call: Call, e: IOException) {
            message.message = e.toString()
            message.code = GameReceiveMessage.ERROR_CODE_HTTP_ERROR
            //消息发送给游戏
            sendToJs(message)
        }

        override fun onResponse(call: Call, response: okhttp3.Response) {
            try {
                val bodyStr = response.getStringBody()
                    ?.replace(" ", "")
                    ?.replace("{}", "null")
                if (bodyStr.isNullOrBlank()) {
                    onFailure(call, IOException(response.message))
                } else {
                    if (BuildConfig.DEBUG) {
                        Logger.v("-------------返回数据---------------")
                        Logger.v(bean.api)
                        Logger.json(bodyStr)
                    }
                    updateAssets(bodyStr)
                    bean.data = bodyStr
                    message.json = gson.toJson(bean)
                    //消息发送给游戏
                    sendToJs(message)
                }
            } catch (e: Throwable) {
                e.printStackTrace()
                onFailure(call, IOException(e.message))
            }
        }
    })
}

/**
 * 更新用户资产信息
 */
private fun updateAssets(str: String) {
    val bean = gson.fromJson<BaseGameBean<Any>>(str, BaseGameBean::class.java)
    if (bean.assets != null) {
        bean.assets.isEnableSendToJs = false
        UserData.userAssetsData.success(bean.assets)
    }
}

private fun GameEgret.testGameLoadFinish() {
    this.gameReceiveMessage.distributeMessages(
        gson.toJson(AndroidJsBean.success(GameReceiveMessage.TYPE_GAME_LOAD_FINISH, ""))
    )
}
